//SharePoint Form Generator 
//By Alon Havivi(havivi@gmail.com, http://havivi.blogspot.com/) 
//For full source code and Terms Of Use,
//visit http://sfg.codeplex.com/

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Collections;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Threading;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.ComponentModel;
using System.Xml.Serialization;
using Microsoft.SharePoint.WebPartPages;
using CMS.SharePoint.CFT_RegEx;
using System.Text.RegularExpressions;


namespace SFG
{
    [Guid("6e9cb3c7-971e-4065-80d0-1eafe8620a7d")]
    public class SharePointFormGenerator : Microsoft.SharePoint.WebPartPages.WebPart
    {


        private bool _error = false;
        private string listName = null;
        private string formTitle = null;
        private string submitButtonUrl = null;
        private string submitButtonCaption = null;
        private string cancelButtonUrl = null;
        private string cancelButtonCaption = null;
        private bool showCancelButton = true;
        private bool showFormTitle = true;



        #region "Properties"



        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("List Name")]
        //[WebDescription("Associate the web part with your list")]
        [Browsable(false), Category("Miscellaneous"),
         DefaultValue(""),
         WebPartStorage(Storage.Shared),
         FriendlyName("List Name"), Description("Associate the web part with your list")]
        public string ListName
        {
            get
            {
                if (listName == null)
                {
                    listName = "";
                }
                return listName;
            }
            set
            {
                listName = value;
            }
        }

        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Form Title")]
        //[WebDescription("Sets the form title. By default, show list name.")]
        [Browsable(false), Category("Miscellaneous"),
         DefaultValue(""),
         WebPartStorage(Storage.Shared),
         FriendlyName("Form Title"), Description("Sets the form title. By default, show list name.")]
        public string FormTitle
        {
            get
            {
                if (formTitle == null)
                {
                    formTitle = "";
                }
                return formTitle;
            }
            set
            {
                formTitle = value;
            }
        }


        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Show Form Title")]
        //[WebDescription("By default, show title.")]
        [Browsable(false), Category("Miscellaneous"),
 DefaultValue(true),
 WebPartStorage(Storage.Shared),
 FriendlyName("Show Form Title"), Description("By default, show title.")]
        public bool ShowFormTitle
        {
            get
            {
                return showFormTitle;
            }
            set
            {
                showFormTitle = value;
            }
        }


        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Submit Button [Url]")]
        //[WebDescription("The url to go to when the submit button is presed. By default, the browser will go to the homepage")]
        [Browsable(false), Category("Miscellaneous"),
DefaultValue(null),
WebPartStorage(Storage.Shared),
FriendlyName("Submit Button [Url]"), Description("The url to go to when the submit button is presed. By default, the browser will go to the homepage")]
        public string SubmitButtonUrl
        {
            get
            {
                if (submitButtonUrl == null)
                {
                    submitButtonUrl = SPContext.Current.Web.Url;
                }
                return submitButtonUrl;
            }
            set
            {
                submitButtonUrl = value;
            }
        }

        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Submit Button [Caption]")]
        //[WebDescription("The caption of the button. The default caption is 'Submit'.")]
        [Browsable(false), Category("Miscellaneous"),
DefaultValue("Submit"),
WebPartStorage(Storage.Shared),
FriendlyName("Submit Button [Caption]"), Description("The caption of the button. The default caption is 'Submit'.")]
        public string SubmitButtonCaption
        {
            get
            {
                if (submitButtonCaption == null)
                {
                    submitButtonCaption = "Submit";
                }
                return submitButtonCaption;
            }
            set
            {
                submitButtonCaption = value;
            }
        }


        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Cancel Button [Url]")]
        //[WebDescription("The url to go to when the cancel button is presed. By default, the browser will go to the homepage")]
        [Browsable(false), Category("Miscellaneous"),
DefaultValue(null),
WebPartStorage(Storage.Shared),
FriendlyName("Cancel Button [Url]"), Description("The url to go to when the cancel button is presed. By default, the browser will go to the homepage")]
        public string CancelButtonUrl
        {
            get
            {
                if (cancelButtonUrl == null)
                {
                    cancelButtonUrl = SPContext.Current.Web.Url;
                }
                return cancelButtonUrl;
            }
            set
            {
                cancelButtonUrl = value;
            }
        }

        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Cancel Button [Caption]")]
        //[WebDescription("The caption of the button. The default caption is 'Cancel'.")]
        [Browsable(false), Category("Miscellaneous"),
DefaultValue("Cancel"),
WebPartStorage(Storage.Shared),
FriendlyName("Cancel Button [Caption]"), Description("The caption of the button. The default caption is 'Cancel'.")]
        public string CancelButtonCaption
        {
            get
            {
                if (cancelButtonCaption == null)
                {
                    cancelButtonCaption = "Cancel";
                }
                return cancelButtonCaption;
            }
            set
            {
                cancelButtonCaption = value;
            }
        }

        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("Form Generator Property")]
        //[WebDisplayName("Show Cancel Button")]
        //[WebDescription("By default, show button.")]
        [Browsable(true), Category("Miscellaneous"),
DefaultValue(true),
WebPartStorage(Storage.Shared),
FriendlyName("Show Cancel Button"), Description("By default, show button.")]
        public bool ShowCancelButton
        {
            get
            {
                return showCancelButton;
            }
            set
            {
                showCancelButton = value;
            }
        }


        #endregion

        /// <summary>
        ///	Gets the custom tool parts for this Web Part by
        ///	overriding the GetToolParts method of the WebPart
        ///	base class. You must implement custom tool parts in
        ///	a separate class that derives from
        ///	Microsoft.SharePoint.WebPartPages.ToolPart.
        ///	</summary>
        ///<returns>
        /// An array of references to ToolPart objects.
        ///</returns>
        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[3];
            WebPartToolPart wptp = new WebPartToolPart();
            CustomPropertyToolPart custom = new CustomPropertyToolPart();
            toolparts[0] = custom;
            toolparts[1] = wptp;

            // This is the custom ToolPart.
            toolparts[2] = new SFG.ToolPart1();

            return toolparts;
        }

        public SharePointFormGenerator()
        {
            this.ExportMode = WebPartExportMode.All;

        }


        //}

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                    this.ChromeType = PartChromeType.None;
                    this.Title = "SharePoint Form Generator";
                    GenerateForm();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }


        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        /// 
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        #region RenderHtml


        public void GenerateForm()
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
          {

              using (SPSite site = new SPSite(SPContext.Current.Site.Url))
              {
                  site.AllowUnsafeUpdates = true;
                  using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                  {
                      web.AllowUnsafeUpdates = true;

                      if (ListName != string.Empty)
                      {
                          SPList list = web.Lists[ListName];
                          if (list.BaseTemplate != SPListTemplateType.GenericList
                              && list.BaseTemplate != SPListTemplateType.Survey
                              && list.BaseTemplate != SPListTemplateType.Tasks
                              && list.BaseTemplate != SPListTemplateType.Contacts
                              && list.BaseTemplate != SPListTemplateType.Announcements
                              && list.BaseTemplate != SPListTemplateType.DiscussionBoard
                              && list.BaseTemplate != SPListTemplateType.Decision
                              && list.BaseTemplate != SPListTemplateType.IssueTracking
                              && list.BaseTemplate != SPListTemplateType.Links)
                          {
                              Label lbl = new Label();
                              lbl.Text = "Can not generate this (" + list.BaseTemplate.ToString() + ") type list.";
                              this.Controls.Add(lbl);
                          }
                          else if (list.Hidden)
                          {
                              Label lbl = new Label();
                              lbl.Text = "The list is hidden.";
                              this.Controls.Add(lbl);
                          }
                          else
                          {
                              Table form = new Table();
                              form = new Table();
                              form.Width = Unit.Percentage(100);
                              form.CssClass = "ms-formtable";
                              form.Style.Add("margin-top", "8px");
                              form.CellPadding = 0;
                              form.CellSpacing = 0;
                              TableRow row = new TableRow();
                              TableCell cell = new TableCell();
                              if (ShowFormTitle)
                              {
                                  if (FormTitle == null || FormTitle == string.Empty)
                                  {
                                      FormTitle = ListName;
                                  }
                                  Label label = new Label();
                                  label.Text = FormTitle;
                                  label.CssClass = "ms-WPTitle";
                                  cell.Controls.Add(label);
                                  cell.ColumnSpan = 2;
                                  row.Cells.Add(cell);
                                  form.Rows.Add(row);
                              }
                              form.Rows.Add(LineRow(1));
                              list.AllowEveryoneViewItems = true;
                              FormField formField = null;
                              TextBox textField = null;
                              FieldLabel labelField;


                              foreach (SPField field in list.Fields)
                              {
                                  //bool showinNew = (bool)field.ShowInNewForm;
                                  if (!field.Hidden && !field.ReadOnlyField && field.Type != SPFieldType.Attachments && field.Type != SPFieldType.File)
                                  {
                                      //if (field.Title == "Title")
                                      //{

                                      labelField = new FieldLabel();
                                      labelField.ControlMode = SPControlMode.New;
                                      labelField.ListId = list.ID;
                                      labelField.FieldName = field.InternalName;



                                      if (field.Type == SPFieldType.Text || field.Type == SPFieldType.Note || field.TypeAsString == "CustomFieldTypeRegEx")
                                      {
                                          formField = new FormField();
                                          formField.ControlMode = SPControlMode.Edit;
                                          formField.ListId = list.ID;
                                          formField.FieldName = field.InternalName;
                                          textField = new TextBox();

                                          if (field.Type == SPFieldType.Note)
                                          {
                                              try
                                              {
                                                  RichTextField orgTextField = (RichTextField)formField.Controls[0];
                                                  textField.CssClass = orgTextField.CssClass;
                                              }
                                              catch { }


                                          }
                                          else
                                          {
                                              TextField orgTextField = (TextField)formField.Controls[0];
                                              textField.CssClass = orgTextField.CssClass;

                                          }


                                          textField.ID = "sfg_" + field.InternalName;
                                          if (field.Type == SPFieldType.Note)
                                          {
                                              textField.TextMode = TextBoxMode.MultiLine;
                                              textField.Rows = 6;
                                          }

                                      }
                                      else
                                      {
                                          formField = new FormField();
                                          formField.ControlMode = SPControlMode.Edit;
                                          formField.ListId = list.ID;
                                          formField.FieldName = field.InternalName;
                                          formField.ID = "sfg_" + field.InternalName;
                                      }
                                      TableRow oRow = new TableRow();
                                      form.Rows.Add(oRow);
                                      TableCell oCellLabel = new TableCell();
                                      oCellLabel.VerticalAlign = VerticalAlign.Top;
                                      oRow.Cells.Add(oCellLabel);
                                      TableCell oCellControl = new TableCell();
                                      oRow.Cells.Add(oCellControl);
                                      oCellLabel.Controls.Add(labelField);
                                      if (field.Type == SPFieldType.Text || field.Type == SPFieldType.Note || field.TypeAsString == "CustomFieldTypeRegEx")
                                      {
                                          oCellControl.Controls.Add(textField);
                                          Label labelValidation = new Label();
                                          labelValidation.CssClass = "ms-formvalidation";
                                          labelValidation.ID = "sfg_" + field.InternalName + "Validation";
                                          oCellControl.Controls.Add(labelValidation);

                                      }
                                      else
                                      {
                                          oCellControl.Controls.Add(formField);
                                      }
                                      oCellLabel.CssClass = "ms-formlabel";
                                      oCellControl.CssClass = "ms-formbody";

                                  }
                                  //  }

                              }
                              form.Rows.Add(LineRow(2));
                              form.Rows.Add(SubmitButtonRow());
                              this.Controls.Add(form);


                          }
                      }
                      else
                      {
                          Label lbl = new Label();
                          lbl.Text = "<b>Associate the web part with your list</b> - On edit page, click the 'Modify Shared Web Part' menu item on the edit drop-down menu. Modify Shared Web Part menu. Select your list to associate the web part with your list";
                          this.Controls.Add(lbl);
                      }
                  }
              }
          });

        }


        private TableRow SubmitButtonRow()
        {

            TableRow row = new TableRow();
            TableCell cell = new TableCell();

            row = new TableRow();
            cell = new TableCell();
            Label label = new Label();
            label.Text = "";
            label.ID = "iDFeedbackMsg";
            label.CssClass = "ms-formvalidation";
            cell.Controls.Add(label);
            row.Cells.Add(cell);

            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Right;
            // cell.ColumnSpan = 2;
            Button buttonSubmit = new Button();
            buttonSubmit.CssClass = "ms-ButtonHeightWidth";
            buttonSubmit.Text = SubmitButtonCaption;
            buttonSubmit.Click += new EventHandler(btnSubmit_Click);
            buttonSubmit.Style.Add("margin-top", "10px");
            buttonSubmit.ID = "btnSubmit";
            cell.Controls.Add(buttonSubmit);

            if (ShowCancelButton)
            {
                label = new Label();
                label.Text = " ";
                cell.Controls.Add(label);
                Button buttonCancel = new Button();
                buttonCancel.CssClass = "ms-ButtonHeightWidth";
                buttonCancel.Style.Add("margin-top", "10px");
                buttonCancel.Text = CancelButtonCaption;
                buttonCancel.ID = "btnCancel";
                buttonCancel.Click += new EventHandler(btnCancel_Click);
                cell.Controls.Add(buttonCancel);
            }

            row.Cells.Add(cell);

            return row;

        }

        private TableRow LineRow(int width)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.ColumnSpan = 2;
            cell.Height = Unit.Pixel(width);
            cell.CssClass = "ms-sectionline";
            Image img = new Image();
            img.ImageUrl = "/_layouts/images/blank.gif";
            img.Height = Unit.Pixel(width);
            img.Width = Unit.Pixel(width);
            cell.Controls.Add(img);
            row.Cells.Add(cell);

            return row;
        }

        #endregion

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            SPUser currentUser = SPContext.Current.Web.CurrentUser;
            try
            {
                if (FormValidation())
                {

                    HandlerSubmit();
                }
            }
            catch (ThreadAbortException)
            {
                // Calling redirect throws a ThreadAbortException which will
                // flag an error in the next step if we don't do this.
                throw;

            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

        }

        private void HandlerSubmit()
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
          {
              using (SPSite site = new SPSite(SPContext.Current.Site.Url))
              {
                  site.AllowUnsafeUpdates = true;
                  using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                  {
                      web.AllowUnsafeUpdates = true;

                      SPList list = web.Lists[listName];
                      SPListItemCollection listItems = list.Items;
                      SPListItem item = listItems.Add();
                      foreach (SPField field in list.Fields)
                      {

                          if (!field.Hidden && !field.ReadOnlyField && field.Type != SPFieldType.Attachments)
                          {
                              if (field.Type == SPFieldType.Text || field.Type == SPFieldType.Note || field.TypeAsString == "CustomFieldTypeRegEx")
                              {
                                  TextBox formField = (TextBox)FindControl("sfg_" + field.InternalName);
                                  if (formField != null)
                                  {
                                      item[field.Title] = formField.Text;
                                  }
                              }
                              else
                              {
                                  FormField formField = (FormField)FindControl("sfg_" + field.InternalName);

                                  if (formField != null)
                                  {

                                      item[field.Title] = formField.Value;
                                  }
                              }
                          }
                      }


                      SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();
                      SPUser user = SPContext.Current.Web.CurrentUser;
                      fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name));
                      item["Author"] = fieldValues;
                      item["Editor"] = fieldValues;
                      item.Update();

                      web.AllowUnsafeUpdates = false;
                      site.AllowUnsafeUpdates = false;
                  }
              }
          });
            SPUtility.Redirect(SubmitButtonUrl, SPRedirectFlags.UseSource, HttpContext.Current);
        }

        /// <summary>
        /// This function will create a SPFieldUserValueCollection on the basis of a 
        /// PeoplePicker-control's Entities collection.
        /// </summary>
        /// <param name="item">The SPListItem being used in the site creation process</param>
        /// <param name="fieldUser">A reference to the SPFieldUser-field</param>
        /// <param name="peEntities">The Entities-collection to be processed</param>
        /// <returns></returns>

        public static SPFieldUserValueCollection GetFieldUserValues(SPListItem item, SPFieldUser fieldUser, ArrayList peEntities)
        {
            if (!fieldUser.AllowMultipleValues)
            {
                fieldUser.AllowMultipleValues = true;
                fieldUser.Update();
            }

            SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();

            foreach (PickerEntity pe in peEntities)
            {
                SPUser user = SPContext.Current.Site.RootWeb.EnsureUser(pe.Key);
                fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name));
            }

            return fieldValues;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SPUtility.Redirect(CancelButtonUrl, SPRedirectFlags.UseSource, HttpContext.Current);
        }

        private bool FormValidation()
        {
            bool returnValue = true;

            SPSecurity.RunWithElevatedPrivileges(delegate()
          {
              using (SPSite site = new SPSite(SPContext.Current.Site.Url))
              {
                  site.AllowUnsafeUpdates = true;
                  using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                  {
                      web.AllowUnsafeUpdates = true;

                      SPList list = web.Lists[listName];


                      foreach (SPField field in list.Fields)
                      {
                          if (!field.Hidden && !field.ReadOnlyField && field.Type != SPFieldType.Attachments && field.Type != SPFieldType.File)
                          {
                              if (field.Required)
                              {


                                  if (field.Type == SPFieldType.Text || field.Type == SPFieldType.Note || field.TypeAsString == "CustomFieldTypeRegEx")
                                  {
                                      Label labelValidation = (Label)FindControl("sfg_" + field.InternalName + "Validation");
                                      TextBox formField = (TextBox)FindControl("sfg_" + field.InternalName);
                                      if (formField != null)
                                      {
                                          if (formField.Text == "")
                                          {
                                              returnValue = false;
                                             
                                              labelValidation.Text = "<BR />You must specify a value for this required field.";
                                          }
                                          else
                                          {
                                              labelValidation.Text = "";
                                          }
                                      }

                                     


                                  }

                              }

                              if (field.TypeAsString == "CustomFieldTypeRegEx")
                              {
                                  Label labelValidation = (Label)FindControl("sfg_" + field.InternalName + "Validation");
                                  TextBox formField = (TextBox)FindControl("sfg_" + field.InternalName);
                                  CustomFieldTypeRegEx cf = (CustomFieldTypeRegEx)field;
                                  Regex reg = new Regex(cf.propRegularExpression, RegexOptions.IgnoreCase);
                                  if (!reg.IsMatch(formField.Text))
                                  {
                                      returnValue = false;
                                      
                                      labelValidation.Text = "</br>" + cf.propErrorMessage;
                                     
                                  }
                                  else
                                  {
                                      labelValidation.Text = "";
                                  }

                              }
                          }
                      }
                  }
              }
          });

            return returnValue;
        }

    }

    /// <summary>
    /// Description of the toolpart. Override the GetToolParts method
    /// in your Web Part class to invoke this toolpart. To establish
    /// a reference to the Web Part the user has selected, use the
    /// ParentToolPane.SelectedWebPart property.
    /// </summary>
    public class ToolPart1 :
    Microsoft.SharePoint.WebPartPages.ToolPart
    {
        // declaring a sample varialble
        DropDownList listDropDownList = new DropDownList();
        TextBox txtFormTitle = new TextBox();
        CheckBox cbShowFormTitle = new CheckBox();
        TextBox txtSubmitButtonUrl = new TextBox();
        TextBox txtSubmitButtonCaption = new TextBox();
        CheckBox cbShowCancelButton = new CheckBox();
        TextBox txtCancelButtonUrl = new TextBox();
        TextBox txtCancelButtonCaption = new TextBox();

        SharePointFormGenerator wp1 = null;

        public ToolPart1()
        {
            // Set default properties
            this.Title = "Form Generator Properties";

        }
        ///	<summary>
        ///	Called by the tool pane to apply property changes to
        /// the selected Web Part.
        ///	</summary>
        public override void ApplyChanges()
        {
            wp1.ListName = listDropDownList.SelectedValue;
            wp1.FormTitle = txtFormTitle.Text;
            wp1.ShowFormTitle = cbShowFormTitle.Checked;
            wp1.SubmitButtonUrl = txtSubmitButtonUrl.Text;
            wp1.SubmitButtonCaption = txtSubmitButtonCaption.Text;
            wp1.ShowCancelButton = cbShowCancelButton.Checked;
            wp1.CancelButtonUrl = txtCancelButtonUrl.Text;
            wp1.CancelButtonCaption = txtCancelButtonCaption.Text;

            wp1.Controls.Clear();
            wp1.GenerateForm();
        }

        /// <summary>
        ///	If the ApplyChanges method succeeds, this method is
        /// called by the tool pane to refresh the specified
        /// property values in the toolpart user interface.
        /// </summary>
        public override void SyncChanges()
        {
            // sync with the new property changes here
        }

        /// <summary>
        ///	Called by the tool pane if the user discards changes
        /// to the selected Web Part.
        /// </summary>
        public override void CancelChanges()
        {
        }

        protected override void CreateChildControls()
        {
            // Get the instance of the web part
            wp1 = (SharePointFormGenerator)ParentToolPane.SelectedWebPart;

            //const string DesignFormWin = "<a onclick=\"javascript:window.showModalDialog('/_layouts/SFG/SFGDesignForm.aspx?id={0}','','dialogWidth=400px;dialogHeight=400px;center=yes;help=no;scroll=no;status=no;');\" class=\"ms-toolbar\"  onmouseover=\"this.style.cursor='hand';\" >";


            string webUrl = string.Empty;
            string url = string.Empty;

            //Create dropdown List
            listDropDownList = new DropDownList();
            //Populate the List
            SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             listDropDownList.Items.Clear();
             listDropDownList.Items.Add("");
             using (SPSite site = new SPSite(SPContext.Current.Site.Url))
             {

                 using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                 {
                     webUrl = web.Url;
                     url = "http://" + this.Page.Request.ServerVariables["SERVER_NAME"] + this.Page.Request.ServerVariables["URL"];
                     foreach (SPList list in web.Lists)
                     {
                         if ((list.BaseTemplate == SPListTemplateType.GenericList
                             || list.BaseTemplate == SPListTemplateType.Survey
                             || list.BaseTemplate == SPListTemplateType.Tasks
                             || list.BaseTemplate == SPListTemplateType.Contacts
                             || list.BaseTemplate == SPListTemplateType.Announcements
                             || list.BaseTemplate == SPListTemplateType.DiscussionBoard
                             || list.BaseTemplate == SPListTemplateType.Decision
                             || list.BaseTemplate == SPListTemplateType.IssueTracking
                             || list.BaseTemplate == SPListTemplateType.Links)
                             && list.Hidden == false)
                         {
                             listDropDownList.Items.Add(list.Title);
                         }
                     }

                 }
             }
         });
            Label lbl = new Label();
            if (listDropDownList.Items.Count > 1)
            {
                Table tbl = new Table();
                tbl.Width = Unit.Percentage(100);
                TableRow row = new TableRow();
                TableCell cell = new TableCell();


                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>List:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                listDropDownList.SelectedValue = wp1.ListName;
                cell.Controls.Add(listDropDownList);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>Form Title:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                txtFormTitle.Text = wp1.FormTitle;
                cell.Controls.Add(txtFormTitle);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>";
                cell.Controls.Add(lbl);
                cbShowFormTitle.Text = "Show Form Title";
                cbShowFormTitle.Checked = wp1.ShowFormTitle;
                cell.Controls.Add(cbShowFormTitle);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>Submit Button Url:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                txtSubmitButtonUrl.Text = wp1.SubmitButtonUrl;
                cell.Controls.Add(txtSubmitButtonUrl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>Submit Button Caption:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                txtSubmitButtonCaption.Text = wp1.SubmitButtonCaption;
                cell.Controls.Add(txtSubmitButtonCaption);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>Cancel Button Url:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                txtCancelButtonUrl.Text = wp1.CancelButtonUrl;
                cell.Controls.Add(txtCancelButtonUrl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>Cancel Button Caption:";
                cell.Controls.Add(lbl);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                txtCancelButtonCaption.Text = wp1.CancelButtonCaption;
                cell.Controls.Add(txtCancelButtonCaption);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                row = new TableRow();
                cell = new TableCell();
                lbl = new Label();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV>";
                cell.Controls.Add(lbl);
                cbShowCancelButton.Text = "Show Cancel Button";
                cbShowCancelButton.Checked = wp1.ShowCancelButton;
                cell.Controls.Add(cbShowCancelButton);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);

                this.Controls.Add(tbl);

                lbl = new Label();
                //Set the text
                //lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\">" + String.Format(DesignFormWin, "") + "Open window</a> </div>";
                Guid gId = Guid.NewGuid();
                string guid = gId.ToString();
                lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV><a onclick=\"javascript:window.showModalDialog('/_layouts/SFG/SFGDesignForm.aspx?id=" + wp1.ID + "&url=" + url + " &uid=" + guid + "','','dialogWidth=400px;dialogHeight=400px;center=yes;help=no;scroll=no;status=no;');\" class=\"ms-toolbar\"  onmouseover=\"this.style.cursor='hand';\" >Design your form</a> ";
                // lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV><a target='_blank' href='/_layouts/SFG/SFGDesignForm.aspx?id=" + wp1.ID + "&uid=" + new Guid().ToString() + "' class=\"ms-toolbar\"  onmouseover=\"this.style.cursor='hand';\" >Open window 1</a> ";
                //
                this.Controls.Add(lbl);

            }
            else
            {
                lbl = new Label();
                //Set the text
                lbl.Text = "</br>First you need to <a href='" + webUrl + "/_layouts/create.aspx'><b>create</b></a> a custom list containing your form fields, then you can associate the web part with your custom list.";
                this.Controls.Add(lbl);
            }

            lbl = new Label();
            //Set the text
            lbl.Text = "<DIV class=\"UserDottedLine\" style=\"WIDTH: 100%\"></DIV></br></br></br><div align='center'><b>SharePoint Form Generator <br> By <a href='mailto:havivi@gmail.com'>Alon Havivi</a><br><a href='http://havivi.blogspot.com'>SharePoint Developer Blog</a></b></div>";
            this.Controls.Add(lbl);

        }
    }

}
